package org.ben.queue;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.SynchronousQueue;

public class SyncQueueTest {
    public static void main(String[] arg) {
        BlockingQueue<String> queue = new SynchronousQueue<String>(false);
        int i = 0;
        
        while(i < 10) {
            Producer p = new Producer("Producer - " + i, queue);
            Consumer c = new Consumer("Consumer - " + i, queue);
            i++;
            Thread t1 = new Thread(p);
            Thread t2 = new Thread(c);
            t1.start();
            t2.start();
        }
    }
}

class Producer implements Runnable {
    private String name;
    private BlockingQueue<String> queue;

    Producer(String n, BlockingQueue<String> queue) {
        this.name = n;
        this.queue = queue;
    }

    public void run() {
        System.out.println(name + " putting...");
        try {
            queue.put(name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
    
}

class Consumer implements Runnable {
    private String name;
    private BlockingQueue<String> queue;

    Consumer(String n, BlockingQueue<String> queue) {
        this.name = n;
        this.queue = queue;
    }

    public void run() {
        System.out.println(name + " waiting...");
        String prod = null;
        try {
            prod = queue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        if(null != prod)
            System.out.println(name +  " , " + prod);
    }
    
}
